package com.alibaba.hsf.guide.router;

import com.taobao.hsf.annotation.Name;
import com.taobao.hsf.annotation.Order;
import com.taobao.hsf.cluster.AbstractSingleTargetRouter;
import com.taobao.hsf.cluster.Router;
import com.taobao.hsf.cluster.RouterFactory;
import com.taobao.hsf.invocation.Invocation;
import com.taobao.hsf.protocol.ServiceURL;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author weipeng2k 2018年05月18日 下午16:14:20
 */
@Order(600)
@Name("oddRouter")
public class OddRouter extends AbstractSingleTargetRouter {

    private Map<String, Router> routerMap = new HashMap<String, Router>();

    @Override
    public void setServiceURLs(List<ServiceURL> addresses) {
        super.setServiceURLs(addresses);
        List<ServiceURL> oddList = new ArrayList<ServiceURL>();
        List<ServiceURL> evenList = new ArrayList<ServiceURL>();

        try {
            for (ServiceURL address : addresses) {
                System.out.println("OddRouter --> Process ip " + address.getHost());
                int i = Integer.parseInt(address.getHost().split("\\.")[0]);
                System.out.println("OddRouter --> process value " + i);
                System.out.println("OddRouter --> value to key " + i % 2);
                if (i % 2 == 1) {
                    System.out.println("OddRouter --> add ip " + address.getHost() + " to odd list");
                    oddList.add(address);
                } else {
                    evenList.add(address);
                    System.out.println("OddRouter --> add ip " + address.getHost() + " to even list");
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        routerMap.get("1").setServiceURLs(oddList);
        routerMap.get("0").setServiceURLs(evenList);
    }

    @Override
    public void setRouterFactory(RouterFactory routerFactory) {
        super.setRouterFactory(routerFactory);

        Router oddRouter = routerFactory.createRouter();
        oddRouter.setName("oddRouter");
        routerMap.put("1", oddRouter);

        Router evenRouter = routerFactory.createRouter();
        evenRouter.setName("oddRouter");
        routerMap.put("0", evenRouter);
    }

    @Override
    protected Router selectRouter(Invocation invocation) {
        Long id = (Long) invocation.getMethodArgs()[0];
        System.out.println("OddRouter --> query order id " + id);
        int value = (int) (id % 2);
        System.out.println("OddRouter --> got value " + value);

        Router router = routerMap.get(String.valueOf(value));

        System.out.println("OddRouter --> router address list : " + router.getServiceURLs());

        return router;
    }

    @Override
    public Map<String, Router> getSubRouterMap() {
        return routerMap;
    }
}
